<?php
/**
 * Created by PhpStorm.
 * Script Name: Bottask.php
 * Create: 2020/5/24 上午10:25
 * Description: 任务
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use app\common\service\Media;
use plugin\wechat\app\model\BotTask as TaskM;
use plugin\wechat\app\service\BotTask as TaskService;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\service\BotFriend as FriendService;
use Support\Request;

class Bottask extends BotBase
{
    /**
     * @var TaskM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new TaskM();
    }

    private function tabList(){
        return [
            'todo' => [
                'title' => '待发送',
                'href' => url('index', ['name' => 'todo'])
            ],
            'done' => [
                'title' => '已发送',
                'href' => url('index', ['name' => 'done'])
            ],
        ];
    }

    /**
     * 列表
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $name = input('name', 'todo');
        $bot = $this->bot;
        if (request()->isPost()) {
            $post_data = input('post.');
            $view_table = $this->model->field('id')
                ->where('company_id', TenantService::getCompanyId())
                ->where('bot_id' , $bot['id']);
            !empty($post_data['search_key']) && $view_table = $view_table->where('title', 'like', '%' . $post_data['search_key'] . '%');
            if($name == 'todo'){
                $view_table = $view_table->where('(complete_time=0 and circle='.TaskService::CIRCLE_SINGLE . ') or circle='.TaskService::CIRCLE_DAILY);
                $order = ['t.plan_time' => 'asc'];
            }else{
                $view_table = $view_table->where('complete_time>0 and circle='.TaskService::CIRCLE_SINGLE);
                $order = ['t.complete_time' => 'desc'];
            }
            $view_table = $view_table->buildSql();
            $query = $this->model->alias('t')
                ->join($view_table . ' t1', 't1.id=t.id');

            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order($order)
                    ->field(['t.*'])
                    ->select();
                foreach ($list as $k => $v){
                    $ids = explode(',', $v['wxids']);
                    if($member = FriendService::getMember($ids[0], $bot['uin'])){
                        $v['wxids'] = $member['nickname'];
                        if(count($ids) > 1){
                            $v['wxids'] .= "等".count($ids)."个对象";
                        }
                    }else{
                        $v['wxids'] = "--";
                    }

                    if($v['medias']){
                        $v['medias'] = json_decode($v['medias'], true);
                        $materials = [];
                        foreach ($v['medias'] as $item){
                            if($material = Media::getMedia(['type' => $item['type'], 'id' => $item['id']])){
                                $materials[] = $item['type'] == 'text' ? $material['content'] : $material['title'];
                            }
                        }
                        $v['content'] = implode('、', $materials);
                    }else{
                        $v['content'] = '';
                    }
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }

            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '内容']
        ])
            ->setTabNav($this->tabList(), $name)
            ->setDataUrl(url('index', ['name' => $name]))
            ->addTopButton('addnew', ['title' => '新增群发', 'text' => '新增群发'])
            ->addTableColumn(['title' => 'ID', 'field' => 'id', 'minWidth' => 60])
            ->addTableColumn(['title' => '任务名称', 'field' => 'title', 'minWidth' => 60])
            ->addTableColumn(['title' => '发送类型', 'field' => 'circle', 'minWidth' => 100, 'type' => 'enum', 'options' => TaskService::circles()])
            ->addTableColumn(['title' => '回复内容', 'field' => 'content', 'minWidth' => 100])
            ->addTableColumn(['title' => '发送对象', 'field' => 'wxids', 'minWidth' => 100])
            ->addTableColumn(['title' => '计划发送时间', 'field' => 'plan_time', 'minWidth' => 180, 'type' => 'datetime']);
        if($name == 'done'){
            $builder->addTableColumn(['title' => '完成时间', 'field' => 'complete_time', 'minWidth' => 180, 'type' => 'datetime'])
                ->addTableColumn(['title' => '操作', 'minWidth' => 90, 'type' => 'toolbar'])
                ->addRightButton('self',['title' => '重发', 'class' => 'layui-btn-normal','href' => url('resetPost', ['id' => '__data_id__']), 'data-ajax' => 1, 'data-confirm' => 1]);
        }else{
            $builder->addTableColumn(['title' => '是否开启', 'field' => 'status', 'minWidth' => 70, 'type' => 'switch', 'options' => [0 => '停止', 1 => '开启']])
                ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
                ->addRightButton('edit');
        }

        return $builder->show();
    }

    /**
     * 重置任务
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function resetPost()
    {
        $id = input('id', null);
        $data = $this->model->where([$this->tenantWhere()])
            ->find($id);

        if (!$data) {
            return $this->error('参数错误');
        }
        $this->model->update([
            'id' => $id,
            'complete_time' => 0
        ]);
        return $this->success('操作成功');
    }

    public function add()
    {
        $default = [
            'plan_time' => date('Y-m-d H:i:s'),
            'circle' => TaskService::CIRCLE_SINGLE,
            'atall' => 0
        ];
        $material = [];
        $members = FriendService::getWxidToNickname();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增')
            ->setPostUrl(url('savePost'))
            ->addFormItem('title', 'text', '任务名称', '选填，不超过30字', [], 'maxlength=30')
            ->addFormItem('circle', 'radio', '发送类型', '发送类型', TaskService::circles())
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则默认当前时间，发送类型选择“每天发送”时，会忽略日期而只取时间段', [], '')
            ->addFormItem('media', 'choose_media_multi', '选择素材', '选择素材', ['types' => Media::types()], 'required')
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '不填则默认针对所有好友和群', $members)
            ->addFormItem('atall', 'radio', '艾特全体', '指定对象为群组才有效', [0 => '否', 1 => '是'], 'required')
        ->setFormData($default);

        return $builder->show(['material' => $material]);
    }

    public function edit()
    {
        $id = input('id', null);
        $data = $this->model->where([$this->tenantWhere()])
            ->find($id);

        if (!$data) {
            return $this->error('参数错误');
        }
        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $materials = [];
        if($data['medias']){
            $data['medias'] = json_decode($data['medias'], true);
            foreach ($data['medias'] as $item){
                $m = Media::getMedia(['type' => $item['type'], 'id' => $item['id']]);
                $m['type'] = $item['type'];
                $materials[] = $m;
            }
        }

        $members = FriendService::getWxidToNickname();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('编辑')
            ->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('title', 'text', '任务名称', '选填，不超过30字', [], 'maxlength=30')
            ->addFormItem('circle', 'radio', '发送类型', '发送类型', TaskService::circles())
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则默认当前时间，发送类型选择“每天发送”时，会忽略日期而只取时间段', [], '')
            ->addFormItem('media', 'choose_media_multi', '选择素材', '可多选', ['types' => Media::types(), 'materials' => $materials], 'required')
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '不填则默认针对所有好友和群', $members)
            ->addFormItem('atall', 'radio', '艾特全体', '指定对象为群组才有效', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'])
            ->setFormData($data);

        return $builder->show();
    }

    public function savePost(Request $request, $jump_to = '', $data = [])
    {
        $post_data = input('post.');
        $post_data['company_id'] = TenantService::getCompanyId();
        $post_data['bot_id'] = $this->bot['id'];
        if(empty($post_data['plan_time'])){
            $post_data['plan_time'] = time();
        }else{
            $post_data['plan_time'] = strtotime($post_data['plan_time']);
        }
        $post_data['plan_hour'] = date('H:i', $post_data['plan_time']);
        if(count($post_data['media_id_type']) > 0){
            $medias = [];
            foreach ($post_data['media_id_type'] as $id_type){
                list($id, $type) = explode('_', $id_type);
                $medias[] = ['id' => $id, 'type' => $type];
            }
            $post_data['medias'] = json_encode($medias, JSON_UNESCAPED_UNICODE);
            unset($post_data['media_id_type']);
        }else{
            return $this->error('请选择素材!');
        }
        if(empty($post_data[$this->pk])){
            $res = $this->model->createOne($post_data);
        }else {
            $res = $this->model->update($post_data);
        }
        if($res){
            return $this->success('数据保存成功!', $jump_to);
        }else{
            return $this->error('数据保存出错!', '', ['token' => token()]);
        }
    }
}